import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import legacy from '@vitejs/plugin-legacy'
import fs from 'fs'
import path from 'path'
import UnoCSS from 'unocss/vite'
import presetUno from '@unocss/preset-uno'
import presetAttributify from '@unocss/preset-attributify'
import presetIcons from '@unocss/preset-icons'
import transformerDirectives from '@unocss/transformer-directives'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'

// 自定义插件，处理动态导入问题
function handleImportPlugin() {
  const virtualModuleId = 'virtual:fix-imports'
  const resolvedVirtualModuleId = '\0' + virtualModuleId
  
  return {
    name: 'vite-plugin-fix-imports',
    enforce: 'pre',
    resolveId(id, importer) {
      // 处理相对路径导入，检查是否需要添加扩展名
      if (id.startsWith('./') || id.startsWith('../')) {
        if (importer) {
          const importerDir = path.dirname(importer)
          const absolutePath = path.resolve(importerDir, id)
          
          // 尝试不同的扩展名
          const extensions = ['.vue', '.js', '.jsx', '.ts', '.tsx']
          for (const ext of extensions) {
            const pathWithExt = `${absolutePath}${ext}`
            if (fs.existsSync(pathWithExt)) {
              return pathWithExt
            }
            
            // 检查是否是目录，如果是，尝试index文件
            if (fs.existsSync(absolutePath) && fs.statSync(absolutePath).isDirectory()) {
              for (const indexExt of extensions) {
                const indexPath = path.join(absolutePath, `index${indexExt}`)
                if (fs.existsSync(indexPath)) {
                  return indexPath
                }
              }
            }
          }
        }
      }
      return null
    }
  }
}

// 自定义分块策略
const customManualChunks = (id) => {
  // 将常用库分离为单独的chunk
  if (id.includes('node_modules')) {
    if (id.includes('vue') || id.includes('pinia')) {
      return 'vendor-vue'
    }
    if (id.includes('element-plus')) {
      return 'vendor-element'
    }
    if (id.includes('axios') || id.includes('md-editor')) {
      return 'vendor-tools'
    }
    return 'vendor' // 其他依赖
  }
};

export default defineConfig({
  plugins: [
    // 修复UnoCSS重复预设警告，确保只配置一次预设
    UnoCSS({
      presets: [
        presetUno(), 
        presetAttributify(),
        presetIcons({
          scale: 1.2,
          warn: true,
        })
      ],
      transformers: [
        transformerDirectives()
      ],
      shortcuts: [
        // 常用布局
        { 'flex-center': 'flex items-center justify-center' },
        { 'flex-between': 'flex items-center justify-between' },
        { 'flex-col-center': 'flex flex-col items-center justify-center' },
      ],
      theme: {
        colors: {
          // 可以添加自定义颜色
          primary: 'var(--themeBackground)',
          secondary: 'var(--greyFont)',
        },
      },
    }),
    handleImportPlugin(),
    vue({
      template: {
        compilerOptions: {
          // 处理一些Vue 2的语法兼容性
          compatConfig: {
            MODE: 2
          }
        }
      }
    }),
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    // 添加打包分析插件
    process.env.ANALYZE === 'true' && visualizer({
      open: true,
      gzipSize: true,
      brotliSize: true,
    }),
    // Gzip压缩
    // viteCompression({
    //   verbose: true,
    //   disable: false,
    //   threshold: 10240,
    //   algorithm: 'gzip',
    //   ext: '.gz',
    // }),
    // // Brotli压缩
    // viteCompression({
    //   verbose: true,
    //   disable: false,
    //   threshold: 10240,
    //   algorithm: 'brotliCompress',
    //   ext: '.br',
    // }),
  ].filter(Boolean), // 过滤掉可能的undefined值
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  },
  build: {
    // 启用CSS代码分割
    cssCodeSplit: true,
    // 禁用源码映射以减小体积
    sourcemap: false,
    // 压缩选项
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,        // 删除所有console.*语句
        drop_debugger: true,       // 删除所有debugger语句
        pure_funcs: [              // 删除指定的函数调用
          'console.log',
          'console.info',
          'console.debug',
          'console.warn',
          'console.error',
          'console.time',
          'console.timeEnd',
          'console.trace'
        ],
        passes: 2,                 // 多次优化
        unused: true,              // 删除未使用的变量和函数
        dead_code: true,           // 删除不可达代码
        conditionals: true,        // 优化if语句
        sequences: true,           // 使用逗号操作符合并语句
        booleans: true,            // 优化布尔表达式
        if_return: true,           // 优化if-return和if-continue
        join_vars: true,           // 合并连续的var语句
        collapse_vars: true,       // 内联可能的变量
        reduce_vars: true,         // 优化变量使用
        toplevel: true,            // 在顶层作用域中进行优化
        hoist_props: true,         // 提升属性访问
        hoist_vars: true,          // 提升变量声明
      },
      mangle: {
        safari10: true,            // Safari 10兼容性
      },
      format: {
        comments: false,           // 删除所有注释
      },
      ecma: 2015,                  // 使用ES2015语法
      toplevel: true,              // 在顶层作用域中进行优化
      safari10: true,              // Safari 10兼容性
    },
    // 设置块大小警告的限制
    chunkSizeWarningLimit: 800,
    rollupOptions: {
      output: {
        // 使用自定义函数进行代码分块
        manualChunks: customManualChunks,
        // 优化静态资源
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.')
          let extType = info[info.length - 1]
          if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'media'
          } else if (/\.(png|jpe?g|gif|svg|ico|webp)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'img'
          } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'fonts'
          }
          return `assets/${extType}/[name]-[hash][extname]`
        },
        // 入口文件与代码分块
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        // 添加跨域属性
        inlineDynamicImports: false,
        // 添加CORS属性
        generatedCode: {
          preset: 'es2015',
          constBindings: true
        }
      }
    },
    commonjsOptions: {
      transformMixedEsModules: true
    }
  },
  optimizeDeps: {
    include: ['vue', 'vue-router', 'pinia', 'axios', 'element-plus', 'md-editor-v3'],
    // 排除不需要预构建的依赖
    exclude: ['vue-demi']
  },
  base: process.env.NODE_ENV === "production" ? "https://cos.roginx.ink/www/blog/index" : "/",
  // base: "/",
  // 开启gzip压缩
  server: {
    host: '127.0.0.1',
    port: 9001,
    cors: true, // 启用CORS，允许跨域请求
    headers: {
      'Access-Control-Allow-Origin': '*', // 允许所有源
    },
    proxy: {
      '/agent': {
        target: 'https://www.roginx.ink/agent',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/agent/, '')
      },
      '/baseagent': {
        target: 'http://127.0.0.1:8085/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/baseagent/, '')
      },
      '/getIp': {
        target: 'http://ip-api.com/json/?lang=zh-CN',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/getIp/, '')
      },
      '/api/alist': {
        target: 'https://alist.roginx.ink/api/',
        changeOrigin: true,
        headers: {
          Host: 'alist.roginx.ink',
          Authorization: ''
        },
        rewrite: (path) => path.replace(/^\/api\/alist/, '/')
      },
      '/api/netapi': {
        target: 'https://www.roginx.ink/api/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      '/api/scrape': {
        target: 'http://service-pjors7ji-1257251314.hk.apigw.tencentcs.com/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api\/scrape/, '/puppeteer'),
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('proxy error', err);
            res.writeHead(500, {
              'Content-Type': 'text/plain',
            });
            res.end('代理请求出错: ' + err.message);
          });
        },
        timeout: 60000,
      },
      '/api/aurora': {
        target: 'http://aurora.roginx.ink/aurora/',
        changeOrigin: true,
        headers: {
          Host: 'aurora.roginx.ink'
        },
        rewrite: (path) => path.replace(/^\/api\/aurora/, '')
      },
      '/api': {
        target: 'https://www.roginx.ink/api/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/')
      },
      '/mapi163/weapi': {
        target: 'http://music.163.com/weapi/',
        rewrite: (path) => path.replace(/^\/mapi163\/weapi/, '/')
      }
    }
  }
}) 